package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/flopp/go-findfont"
	"github.com/goki/freetype/truetype"
	"log"
	"os"
	"tool/yyn"
)

// 初始化--支持中文字体设置
func init() {
	fontPath, err := findfont.Find("simkai.ttf")
	if err != nil {
		panic(err)
	}
	fmt.Printf("字体查找'  '%s'\n", fontPath)

	// load the font with the freetype library
	fontData, err := os.ReadFile(fontPath)
	if err != nil {
		panic(err)
	}
	_, err = truetype.Parse(fontData)
	if err != nil {
		panic(err)
	}
	os.Setenv("FYNE_FONT", fontPath)
}

// 入口
func main() {
	//应用-初始化元数据
	initMetaData()
	//应用-创建
	app := app.NewWithID("main_window")
	//应用-设置logo TODO: 如何更换？
	app.SetIcon(theme.FyneLogo())
	//应用-设置黑色
	app.Settings().SetTheme(theme.DarkTheme())
	//应用-生命周期监听
	logLifecycle(app)

	//主窗口-创建
	mainWindow := app.NewWindow("主控小工具")
	mainWindow.SetMaster()

	//主窗口-布局
	leftUi := mainUI(mainWindow)
	mainWindow.SetContent(leftUi)

	//启动窗口和app
	mainWindow.Resize(fyne.NewSize(1040, 460))
	mainWindow.ShowAndRun()
}

// mainWindow content
func mainUI(win fyne.Window) fyne.CanvasObject {
	currentApp := fyne.CurrentApp()
	//main-right-top-主题
	themes := container.NewGridWithColumns(2,
		widget.NewButton("黑", func() {
			currentApp.Settings().SetTheme(theme.DarkTheme())
		}),
		widget.NewButton("白", func() {
			currentApp.Settings().SetTheme(theme.LightTheme())
		}),
	)
	//main-right-center-tab
	tabs := container.NewAppTabs(
		container.NewTabItem("相机流量估算", yyn.Flow()),
		container.NewTabItem("桩号经纬度换算", yyn.CoordinateUI1(win)),
		container.NewTabItem("kafka拉数据", yyn.KafkaUI(win)),
	)
	tabs.OnSelected = func(tab *container.TabItem) {
		fmt.Println("tab selected:" + tab.Text)
	}
	tabs.SetTabLocation(container.TabLocationLeading)

	return container.NewBorder(themes, nil, nil, nil, tabs)
}

func initMetaData() {
	// app-metaData
	metaData := fyne.AppMetadata{
		ID:      "appId",
		Name:    "appName",
		Version: "0.0.1",
		Build:   1,
		Release: false,
		Custom: map[string]string{
			"author":    "yuyanan",
			"intention": "test",
		},
	}
	app.SetMetadata(metaData)
}

// 应用生命周期监听器
func logLifecycle(a fyne.App) {
	a.Lifecycle().SetOnStarted(func() {
		log.Println("Lifecycle [" + a.UniqueID() + "]: Started")
	})
	a.Lifecycle().SetOnStopped(func() {
		log.Println("Lifecycle [" + a.UniqueID() + "]: Stopped")
	})
	a.Lifecycle().SetOnEnteredForeground(func() {
		log.Println("Lifecycle [" + a.UniqueID() + "]: Entered Foreground")
	})
	a.Lifecycle().SetOnExitedForeground(func() {
		log.Println("Lifecycle [" + a.UniqueID() + "]: Exited Foreground")
	})
}
